import { useUserStore } from '@/store/modules/user.js';
import { needLoginPages as _needLoginPages } from '@/utils';

const loginRoute = '/pages/login/index';

const isLogined = () => {
  const userStore = useUserStore();
  return userStore.isLogined;
};

const navigateToInterceptor = {
  // 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同
  invoke({ url }) {
    const path = url.split('?')[0];
    let needLoginPages = _needLoginPages;

    const isNeedLogin = needLoginPages.includes(path);

    if (!isNeedLogin) {
      return true;
    }

    const hasLogin = isLogined();
    if (hasLogin) {
      return true;
    }

    const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`;
    uni.navigateTo({ url: redirectRoute });
    return false;
  }
};

export const routeInterceptor = {
  install() {
    uni.addInterceptor('navigateTo', navigateToInterceptor);
    uni.addInterceptor('reLaunch', navigateToInterceptor);
    uni.addInterceptor('redirectTo', navigateToInterceptor);
    uni.addInterceptor('switchTab', navigateToInterceptor);
  }
};
